package com.citycloud.ccuap.tc.admin.sec.secuser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.citycloud.ccuap.commons.json.TreeNode;
import com.citycloud.ccuap.commons.sys.deptment.IDeptmentService;
import com.citycloud.ccuap.commons.sys.entity.SysDeptment;
import com.citycloud.ccuap.commons.sys.entity.SysGroup;
import com.citycloud.ccuap.commons.sys.entity.SysProject;
import com.citycloud.ccuap.commons.sys.entity.SysProjectCategory;
import com.citycloud.ccuap.commons.sys.entity.SysProjectManager;
import com.citycloud.ccuap.commons.sys.entity.SysRole;
import com.citycloud.ccuap.commons.sys.entity.SysUser;
import com.citycloud.ccuap.commons.sys.group.IGroupService;
import com.citycloud.ccuap.commons.sys.repository.SysGroupRepository;
import com.citycloud.ccuap.commons.sys.repository.SysProjectCategoryRepository;
import com.citycloud.ccuap.commons.sys.repository.SysProjectManagerRepository;
import com.citycloud.ccuap.commons.sys.repository.SysProjectRepository;
import com.citycloud.ccuap.commons.sys.repository.SysUserRepository;
import com.citycloud.ccuap.commons.sys.role.RoleService;
import com.citycloud.ccuap.commons.sys.user.UserService;
import com.citycloud.ccuap.tc.admin.entity.SysDeptmentMerge;
import com.citycloud.ccuap.tc.admin.entity.SysProjectFunction;
import com.citycloud.ccuap.tc.admin.entity.TableCateDto;
import com.citycloud.ccuap.tc.admin.model.DeptFields;
import com.citycloud.ccuap.tc.admin.model.SecRole;
import com.citycloud.ccuap.tc.admin.model.SecUser;
import com.citycloud.ccuap.tc.admin.model.TreeNodeModel;
import com.citycloud.ccuap.tc.admin.repository.SysDeptmentMergeRepository;
import com.citycloud.ccuap.tc.admin.repository.SysProjectDeptmentRepository;
import com.citycloud.ccuap.tc.admin.repository.SysProjectFunctionRepository;
import com.citycloud.ccuap.tc.admin.repository.SysProjectGroupRepository;
import com.citycloud.ccuap.tc.admin.sec.secrole.SecRoleService;
import com.citycloud.ccuap.tc.yq.entity.SysDimensionTableConfig;
import com.citycloud.ccuap.tc.yq.repository.SysDimensionTableConfigRepository;

@Service
public class SecUserService implements ISecUserService {

    private static Log logger = LogFactory.getLog(SecUserService.class);
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private SecRoleService secRoleService;

    @Autowired
    SysProjectFunctionRepository sysProjectFunctionRepository;

    @Autowired
    private SysGroupRepository sysGroupRepository2;
    
    @Autowired
    private IGroupService groupService;

    @Autowired
    private IDeptmentService deptmentService;

    @Autowired
    private SysProjectRepository sysProjectRepository;

    @Autowired
    private SysProjectManagerRepository sysProjectManagerRepository;

    @Autowired
    private SysProjectCategoryRepository projectCategoryRepository;

    @Autowired
    private SysUserRepository sysUserRepository;

    @Autowired
    private SysProjectGroupRepository sysGroupRepository;

    @Autowired
    private SysProjectDeptmentRepository sysDeptmentRepository;

    @Autowired
    private SysDimensionTableConfigRepository sysDimensionTableConfigRepository;

    @Autowired
    private SecUserCacheService secUserCacheService;

    @Autowired
    private SysDeptmentMergeRepository sysDeptmentMergeRepository;
    
    @Autowired
    @Lazy
    private SecUserMapper secUserMapper;

    /**
     * 获取某机构下拥有指定角色的用户
     *
     * @return
     */
    @Override
    public List<SecUser> getUsersInRoles(String deptId, String projectId, String roleId) {
        Assert.notNull(deptId, "deptId 不能为null");
        Assert.notNull(projectId, "projectNo 不能为null");
        List<SysUser> originUsers = roleService.findUsersById(Long.parseLong(roleId));
        List<SecUser> secUsers = new ArrayList<SecUser>();

        for (SysUser sysUser : originUsers) {
            if (sysUser.getDeptId() == null || sysUser.getProjectId() == null) {
                break;
            } else {
                if (sysUser.getDeptId().equals(Long.parseLong(deptId)) && sysUser.getProjectId().equals(Long.parseLong(projectId))) {
                    //当前用户的机构编号和项目编号与传参一致
                    SecUser secUser = this.changeSysUser(sysUser, String.valueOf(sysUser.getUserId()), projectId);
                    secUsers.add(secUser);
                }
            }
        }
        return secUsers;
    }

    /**
     * 根据userid,appid(当前项目projectId),其余空字段   查询用户信息
     *
     * @return
     */
    @Override
    public SecUser getUser(String userId, String projectId) {
        SysUser sysUser = userService.findById(Long.parseLong(userId));
        SecUser secUser=null;
        if(sysUser!=null) {
            secUser = this.changeSysUser(sysUser, userId, projectId);
        }
        return secUser;
    }

    @Override
    public SecUser getCurrentUser(String userId, String projectId) {
        return this.getUser(userId, projectId);
    }

    /**
     * 12-验证用户是否有指定角色
     *
     * @return
     */
    @Override
    public boolean hasRole(String userId, String projectId, String roleId) {
        boolean hasRole = false;
        //peojectId查询
        List<SysRole> sysRoleList = new ArrayList<SysRole>();
        if (projectId == null || "".equals(projectId) || "null".equals(projectId)) {
            //平台级别
            sysRoleList = userService.findRoleListByUserId(Long.parseLong(userId), null);
        } else {
            //租户级
            sysRoleList = secUserMapper.findRoleListByUserIdAndProjectId(Long.parseLong(userId), Long.parseLong(projectId));
        }
        for (SysRole role : sysRoleList) {
            if (role.getRoleId().equals(Long.parseLong(roleId))) {
                hasRole = true;
                break;
            } else {
                continue;
            }
        }
        return hasRole;
    }

    /**
     * 8-验证用户是否拥有角色列表中的至少一个
     *
     * @return
     */
    @Override
    public boolean hasRoles(String userId, String projectId, List<String> roleIds) {
        boolean hasRole = false;
        List<SysRole> sysRoleList = new ArrayList<SysRole>();
        if (projectId == null || "".equals(projectId) || "null".equals(projectId)) {
            //平台级别
            sysRoleList = userService.findRoleListByUserId(Long.parseLong(userId), null);
        } else {
            //租户级
            sysRoleList = secUserMapper.findRoleListByUserIdAndProjectId(Long.parseLong(userId), Long.parseLong(projectId));
        }
        for (SysRole role : sysRoleList) {
            if (hasRole) {
                break;
            } else {
                for (String roleId : roleIds) {
                    if (roleId.equals(String.valueOf(role.getRoleId()))) {
                        hasRole = true;
                        break;
                    }
                }
            }
        }
        return hasRole;
    }

    /**
     * 验证用户是否拥有角色列表中的所有
     *
     * @return
     */
    @Override
    public boolean hasAllRoles(String userId, String projectId, List<String> roleIds) {
        boolean hasRole = false;

        int hasRoleNum = 0;
        List<SysRole> sysRoleList = new ArrayList<SysRole>();
        if (projectId == null || "".equals(projectId) || "null".equals(projectId)) {
            //平台级别
            sysRoleList = userService.findRoleListByUserId(Long.parseLong(userId), null);
        } else {
            //租户级
            sysRoleList = secUserMapper.findRoleListByUserIdAndProjectId(Long.parseLong(userId), Long.parseLong(projectId));
        }
        for (SysRole role : sysRoleList) {
            for (String roleId : roleIds) {
                if (roleId.equals(String.valueOf(role.getRoleId()))) {
                    hasRoleNum++;
                }
            }
        }
        if (hasRoleNum == roleIds.size()) {
            hasRole = true;
        }
        return hasRole;
    }


    /**
     * sysUser包装成SecUser-根据userid和appid查找对应的角色
     *
     * @return
     */
    public SecUser changeSysUser(SysUser sysUser, String userId, String projectId) {
        SecUser secUser = new SecUser();

//        secUser.setPostId(sysUser.getPostId());
        secUser.setPostId(null);
//        if (sysUser.getUserType() != null) {
//            secUser.setUserTypes(Arrays.asList(sysUser.getUserType().split(",")));
//        }
        secUser.setLawEnforcementId(null);
        secUser.setDept(deptmentService.findById(sysUser.getDeptId()));
        secUser.setGroup(groupService.findById(sysUser.getGroupId()));
        if (null != secUser.getDept() && null != secUser.getGroup()) {
            secUser.setAllPathName(secUser.getGroup().getFullPath() + "\\" + secUser.getDept().getFullPath() + "\\" + sysUser.getUserName());
        }
        //设置基本信息
//        sysUser.setLastLogonTime(null);
        secUser.setOriginalUser(sysUser);
        //设置角色列表(需要包装的SecRole)
        List<SysRole> sysRoleList = new ArrayList<SysRole>();
        if (projectId == null || "".equals(projectId) || "null".equals(projectId)) {
            //无租户信息，项目级
            sysRoleList = userService.findRoleListByUserId(Long.parseLong(userId), null);
        } else {
            //租户级
            sysRoleList = secUserMapper.findRoleListByUserIdAndProjectId(Long.parseLong(userId), Long.parseLong(projectId));
        }
        List<SecRole> secRoleList = new ArrayList<SecRole>();
        for (SysRole sysrole : sysRoleList) {
            Long roleId = sysrole.getRoleId();

            SecRole secRole = new SecRole();
            if (projectId == null || "".equals(projectId) || "null".equals(projectId)) {
                secRole = secRoleService.getSecRoleById(roleId, null, sysrole, false);
            } else {
                secRole = secRoleService.getSecRoleById(roleId, Long.parseLong(projectId), sysrole, false);

            }
            secRoleList.add(secRole);
        }
        secUser.setRoles(secRoleList);
        return secUser;
    }

    @Override
    public List<SysRole> findProjectRoles(String projectId, String userId) {
        return secUserMapper.findProjectRoles(projectId, userId);
    }

    @Override
    public List<SysUser> getUsersByUserName(String userName) {
        return secUserMapper.getUsersByUserName(userName);
    }

    @Override
    public List<SysUser> getUsersByRoleId(Long roleId) {
        return secUserMapper.getUsersByRoleId(roleId);
    }

    @Override
    public List<SysRole> getRolesByProjectId(Long projectId) {
        return secUserMapper.findByProjectId(projectId);
    }

    @Override
    public List<TreeNode> findProjectTreeNodesByRoles(String projectId, String roleIds, String pid) {
        List<TreeNode> results = new ArrayList<>();
        List<SysProjectFunction> funcs = secUserMapper.findProjectFuncsByRoles(projectId, roleIds, pid);
        funcs.forEach(f -> {
            TreeNodeModel node = new TreeNodeModel();
            node.setId(f.getFunId());
            node.setText(f.getFunName());
            node.setExpanded(true);
            node.setUrl(f.getLocation());
            node.setIcon(f.getIcon());
            node.setOrderNo(f.getOrderNo());
            node.setNodeType(f.getFunType());
            node.setSystemType((short) 0);
            node.setHelpUrl(f.getHelpUrl());
            node.setOpenNew(f.getOpenNew());
            node.setRemark(f.getRemark());
            List<TreeNode> childrenNodes = findProjectTreeNodesByRoles(projectId, roleIds, f.getFunId());
            if (childrenNodes.size() > 0) {
                node.setLeaf(false);
                node.setChildren(childrenNodes);
            } else {
                node.setLeaf(true);
            }
            results.add(node);
        });
        return results;
    }

    @Override
    public Set<String> findProjectFunsSetByUserIdandProjectId(Long projectId, Long userId) {
        return secUserMapper.findProjectFunsSetByUserIdandProjectId(projectId, userId);
    }

    @Override
    public List<Map<String, Object>> getSysProjectsByConditions(Long managerId, Long cateId, String name) {
        return secUserMapper.getSysProjectsByConditions(managerId, cateId, name);
    }

    @Override
    public Map<String, Object> getManagersByProjectId(Long projectId) {
        Map<String, Object> result = new HashMap<>();
        SysProject project = sysProjectRepository.findBasicOne(projectId);
        result.put("tenanttName", project.getProjectName());
        result.put("remark", project.getRemark());
        List<SysProjectManager> managers = sysProjectManagerRepository.findByProjectId(projectId);
        managers.forEach((manager) -> {
            StringBuilder sb = new StringBuilder();
            SysUser user = sysUserRepository.findById(Long.valueOf(manager.getManagerId())).get();
            SysGroup group = sysGroupRepository.findById(user.getGroupId()).get();
            SysDeptment deptment = sysDeptmentRepository.findById(user.getDeptId()).get();
            if (null != group) {
                sb.append(group.getFullPath()).append("\\");
            }
            if (null != deptment) {
                sb.append(deptment.getFullPath()).append("\\");
            }
            sb.append(user.getUserName());
            manager.setManagerName(sb.toString());
        });
        result.put("managers", managers);
        return result;
    }

    @Override
    public List<TreeNode> findNextChildNodeTree(Long pid, boolean isAll) {
        List<TreeNode> treeList = new ArrayList<>();
        List<SysProjectCategory> nodeList;
        if (pid == null) {
            nodeList = projectCategoryRepository.findByPidNullOrderByOrderNo();
        } else {
            nodeList = projectCategoryRepository.findByPidOrderByOrderNo(pid);
        }
        if (nodeList != null) {
            for (SysProjectCategory sysProjectCategory : nodeList) {
                TreeNode node = new TreeNode();
                node.setId(sysProjectCategory.getCatId().toString());
                node.setText(sysProjectCategory.getCatName());
                node.setExpanded(true);
                boolean isLeaf = !hasChildNode(sysProjectCategory.getCatId());
                node.setLeaf(isLeaf);
                if (isAll && !isLeaf) {
                    node.setChildren(findNextChildNodeTree(sysProjectCategory.getCatId(), isAll));
                }
                treeList.add(node);
            }
        }
        return treeList;
    }

    /**
     * 父节点下是否存在节点
     *
     * @param pid
     * @return
     */
    private boolean hasChildNode(Long pid) {
        Long count = projectCategoryRepository.countByPid(pid);
        if (count == 0) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public List<SysProject> getProjectsByUserRoles(Long userId) {
        return secUserMapper.getProjectsByUserRoles(userId);
    }

    @Override
    public List<SysProject> getAllProjects() {
        return secUserMapper.getAllProjects();
    }

    @Override
    public List<Map<String, Object>> getDeptTree(String guid, String type, int deep) {
        return getDeptTree(guid, type, 0, deep);
    }

    /**
     * 获取机构树
     *
     * @param guid
     * @param type
     * @param cDeep
     * @param maxDeep
     * @return
     */
    private List<Map<String, Object>> getDeptTree(String guid, String type, int cDeep, int maxDeep) {
        List<Map<String, Object>> result = new ArrayList<>();
        if (StringUtils.isBlank(guid) && StringUtils.isBlank(type)) {
            List<SysGroup> groups = sysGroupRepository.findByPidNullAndOrgGuidNotNullAndDataStatusOrderByOrderNo(1);
            getDeptTreeGroups(groups, result, cDeep, maxDeep);
        } else if (StringUtils.isNotBlank(guid)) {
            if ("1".equals(type)) {
                SysGroup pgroup = sysGroupRepository.findByOrgGuid(guid);
                if (null == pgroup) {
                    return result;
                }
                if (sysGroupRepository.countByPidAndOrgGuidNotNullAndDataStatus(pgroup.getGroupId(), 1) > 0) {
                    List<SysGroup> groups = sysGroupRepository.findByPidAndOrgGuidNotNullAndDataStatusOrderByOrderNo(pgroup.getGroupId(), 1);
                    getDeptTreeGroups(groups, result, cDeep, maxDeep);
                }
                if (sysDeptmentRepository.countByGroupIdAndProjectIdAndDataStatusAndPidNullAndOrgGuidNotNull(pgroup.getGroupId(),
                        10L, 1) > 0) {
                    List<SysDeptment> depts = sysDeptmentRepository.findByPidNullAndOrgGuidNotNullAndGroupIdAndProjectIdAndDataStatusOrderByOrderNo(
                            pgroup.getGroupId(), 10L, 1);
                    getDeptTreeDepts(depts, result, pgroup, cDeep, maxDeep);
                }
            } else if ("2".equals(type)) {
                SysDeptment pdept = sysDeptmentRepository.findByOrgGuid(guid);
                List<SysDeptment> depts = sysDeptmentRepository.findByPidAndProjectIdAndDataStatusAndOrgGuidNotNullOrderByOrderNo(pdept.getDeptId(),
                        10L, 1);
                SysGroup group = sysGroupRepository.findById(pdept.getGroupId()).get();
                getDeptTreeDepts(depts, result, group, cDeep, maxDeep);
            }
        }
        return result;
    }

    private void getDeptTreeGroups(List<SysGroup> groups, List<Map<String, Object>> result, int cDeep, int maxDeep) {
        groups.forEach((group) -> {
            Map<String, Object> g = new HashMap<>();
            g.put(DeptFields.name.name(), group.getGroupName());
            g.put(DeptFields.id.name(), group.getGroupId());
            g.put(DeptFields.deptType.name(), 1);
            g.put(DeptFields.allPathName.name(), group.getFullPath());
            g.put(DeptFields.orgGuid.name(), group.getOrgGuid());
            Long gChildrenSize = sysGroupRepository.countByPidAndOrgGuidNotNullAndDataStatus(group.getGroupId(), 1);
            Long dChildrenSize = sysDeptmentRepository.countByGroupIdAndProjectIdAndDataStatusAndPidNullAndOrgGuidNotNull(group.getGroupId(),
                    10L, 1);
            g.put(DeptFields.isParent.name(), (gChildrenSize + dChildrenSize) > 0);
            if ((gChildrenSize + dChildrenSize) > 0 && (cDeep + 1) < maxDeep) {
                g.put(DeptFields.children.name(), getDeptTree(group.getOrgGuid(), String.valueOf(1), cDeep + 1, maxDeep));
            } else {
                g.put(DeptFields.children.name(), new ArrayList<>());
            }
            result.add(g);
        });
    }

    private void getDeptTreeDepts(List<SysDeptment> depts, List<Map<String, Object>> result, SysGroup group, int cDeep, int maxDeep) {
        depts.forEach((dept) -> {
            Map<String, Object> d = new HashMap<>();
            d.put(DeptFields.name.name(), dept.getDeptName());
            d.put(DeptFields.id.name(), dept.getDeptId());
            d.put(DeptFields.deptType.name(), 2);
            StringBuilder sb = new StringBuilder(group != null ? (group.getFullPath() + "\\") : "")
                    .append(dept.getFullPath());
            d.put(DeptFields.allPathName.name(), sb.toString());
            d.put(DeptFields.orgGuid.name(), dept.getOrgGuid());
            Long childrenSize = sysDeptmentRepository.countByPidAndProjectIdAndDataStatusAndOrgGuidNotNull(dept.getDeptId(), 10L, 1);
            d.put(DeptFields.isParent.name(), childrenSize > 0);
            if (childrenSize > 0 && (cDeep + 1) < maxDeep) {
                d.put(DeptFields.children.name(), getDeptTree(dept.getOrgGuid(), String.valueOf(2), cDeep + 1, maxDeep));
            } else {
                d.put(DeptFields.children.name(), new ArrayList<>());
            }
            result.add(d);
        });
    }

    @Override
    @Caching(evict = {@CacheEvict(value = "dataGroupCache", key = "#p0 + '_' + #p1")})
    public void clearCache(String userId, String projectId) {
        logger.info("清空缓存：" + userId + "-->" + projectId);
    }

    @Override
    @Caching(evict = {@CacheEvict(value = "tableFieldsCache", allEntries = true),
            @CacheEvict(value = "dataGroupCache", allEntries = true),
            @CacheEvict(value = "dataGroupTablesCache", allEntries = true)})
    public void clearAllCache(String userId, String projectId) {
        logger.info("清空全部缓存：" + userId + "-->" + projectId);
    }

    @Override
    public List<Map<String, Object>> getWebSitesByRoleIdAndUserId(String userId, String roleCode) {
        return secUserMapper.getWebSitesByRoleIdAndUserId(userId, roleCode);
    }

    @Override
    @Caching(evict = {@CacheEvict(value = "dataGroupTablesCache", key = "#p0")})
    public void clearCacheDatagroupIdAndProjectId(String datagroupId) {
        logger.info("清空缓存clearCacheDatagroupIdAndProjectId：" + datagroupId);
        List<SysDimensionTableConfig> list = sysDimensionTableConfigRepository.findByDatagroupId(datagroupId);
        list.stream().forEach(x -> {
            clearTableFieldsCache(x.getTableConfigId());
        });
    }


    @Caching(evict = {@CacheEvict(value = "tableFieldsCache", key = "#p0")})
    public void clearTableFieldsCache(String tableConfigId) {
        logger.info("清空缓存clearTableFieldsCache：" + tableConfigId);
    }

    @Override
    public List<SysProject> selectAllProjectByUserId(String userId) {
        return secUserMapper.selectAllProjectByUserId(userId);
    }

    @Override
    public List<TableCateDto> getTablePermissionsByUser(String userId, String projectId, String cateId) {
        Set<String> set = secUserCacheService.getDataPermissionsOfTableByUser(Long.valueOf(userId), Long.valueOf(projectId), null);
        List<String> list = new ArrayList<>(set);
        String tableIds = "";
        for (int i = 0; i < list.size(); i++) {
            if (i == list.size() - 1) {
                tableIds += list.get(i);
            } else {
                tableIds = list.get(i) + ",";
            }
        }
        List<Map<String, String>> tableCateDtos = secUserMapper.getTablePermissionsByUser(cateId, tableIds);
        List<TableCateDto> tableCateDtoList = new ArrayList<>();
        if (tableCateDtos != null && tableCateDtos.size() > 0) {
            for (Map<String, String> map : tableCateDtos) {
                TableCateDto tableCateDto = new TableCateDto();
                tableCateDto.setCateId(map.get("cateId"));
                tableCateDto.setCateName(map.get("cateName"));
                tableCateDto.setTableCname(map.get("tableCname"));
                tableCateDtoList.add(tableCateDto);
            }
        }

        return tableCateDtoList;
    }

    @Override
    public List<SysUser> getManageUserByProjectId(String projectId) {
        return secUserMapper.getManageUserByProjectId(projectId);
    }

    @Override
    public List<SysDeptmentMerge> getDeptmentsByPid(Long pid, boolean refrshCache) {
        List<SysDeptmentMerge> sysDeptmentMerges = new ArrayList<SysDeptmentMerge>();
        List<SysDeptmentMerge> fristParents;
        if (refrshCache) {
            if (-1L == pid) {
                fristParents = sysDeptmentMergeRepository.findListByPidIsNull();
            } else {
                fristParents = sysDeptmentMergeRepository.findListByPid(pid);
            }
        } else {
            if (-1L == pid) {
                fristParents = sysDeptmentMergeRepository.findAllByPidIsNull();
            } else {
                fristParents = sysDeptmentMergeRepository.findAllByPid(pid);
            }
        }

        getDeptmentsByPid(sysDeptmentMerges, fristParents, refrshCache);
        return sysDeptmentMerges;
    }

    private void getDeptmentsByPid(List<SysDeptmentMerge> sysDeptmentMerges, List<SysDeptmentMerge> subSysDeptments, boolean refrshCache) {
        if (null != subSysDeptments && subSysDeptments.size() > 0) {
            for (SysDeptmentMerge subSysDeptment : subSysDeptments) {
                sysDeptmentMerges.add(subSysDeptment);
                List<SysDeptmentMerge> tempSysDeptmentMerges;
                if (refrshCache) {
                    tempSysDeptmentMerges = sysDeptmentMergeRepository.findListByPid(subSysDeptment.getDeptId());
                } else {
                    tempSysDeptmentMerges = sysDeptmentMergeRepository.findAllByPid(subSysDeptment.getDeptId());
                }
                getDeptmentsByPid(sysDeptmentMerges, tempSysDeptmentMerges, refrshCache);
            }
        }
    }

    @Override
    public List<Map<String, Object>> getUsersByDeptId(Long deptId, boolean refrshCache) {
        List<Map<String, Object>> users = new ArrayList<Map<String, Object>>();
        getUsersByDeptId(users, deptId, refrshCache);
        return users;
    }


    private void getUsersByDeptId(List<Map<String, Object>> users, Long deptId, boolean refrshCache) {

        List<Map<String, Object>> temp;
        if (refrshCache) {
            temp = secUserMapper.getListUsersByDeptId(deptId);
        } else {
            temp = secUserMapper.getUsersByDeptId(deptId);
        }
        if (null != temp && temp.size() > 0) {
            users.addAll(temp);
        }
        List<SysDeptmentMerge> tempSysDeptmentMerges;
        if (refrshCache) {
            if (-1L == deptId) {
                tempSysDeptmentMerges = sysDeptmentMergeRepository.findListByPidIsNull();
            } else {
                tempSysDeptmentMerges = sysDeptmentMergeRepository.findListByPid(deptId);
            }
        } else {
            if (-1L == deptId) {
                tempSysDeptmentMerges = sysDeptmentMergeRepository.findAllByPidIsNull();
            } else {
                tempSysDeptmentMerges = sysDeptmentMergeRepository.findAllByPid(deptId);
            }
        }

        if (null != tempSysDeptmentMerges && tempSysDeptmentMerges.size() > 0) {
            for (SysDeptmentMerge tempSysDeptmentMerge : tempSysDeptmentMerges) {
                getUsersByDeptId(users, tempSysDeptmentMerge.getDeptId(), refrshCache);
            }
        }
    }

    @Override
    public List<SysGroup> getAllCustomCode(String oriCustom) {
        return secUserMapper.getAllCustomCode(oriCustom);
    }

    @Override
    public List<SysGroup> findByGroupNo(String groupNo) {
        return secUserMapper.findByGroupNo(groupNo);
    }

    @Override
    public List<TableCateDto> getTablePermissionsByUserNew(String userId, String projectId) {
        List<Map<String, String>> tableCateDtos = secUserMapper.getTablePermissionsByUserNew(userId, projectId);
        List<TableCateDto> tableCateDtoList = new ArrayList<>();
        if (tableCateDtos != null && tableCateDtos.size() > 0) {
            for (Map<String, String> map : tableCateDtos) {
                TableCateDto tableCateDto = new TableCateDto();
                tableCateDto.setCateId(map.get("cateId"));
                tableCateDto.setCateName(map.get("cateName"));
                tableCateDto.setTableCname(map.get("tableCname"));
                tableCateDtoList.add(tableCateDto);
            }
        }
        return tableCateDtoList;
    }
}
